<?php

namespace app\index\controller;
//验证类
use app\index\controller\Auth;
// 缓存
use think\Cache;
use \think\Request;

class Index extends Auth
{

    //需验证方法集
    protected $is_check_login = ['*'];

    // 首页
    public function index()
    {
        // dump($this->getIndexData());
        // exit;
        @NumberHeartbeat();
        // 判断是否开启缓存
        if (getConfig('collectset', 'indexSw') == "true") {
            //获取缓存数据
            $data = Cache::store('cmsindexcache')->get("index");
            //判断缓存数据是否过期
            if (!$data) {
                //获取数据
                $data = $this->getIndexData();
                //判断数据是否正常
                if (isset($data[0]['code']) && $data[0]['code'] == "200") {
                    //数据缓存 时间单位秒
                    Cache::store('cmsindexcache')->set("index", $data, getConfig('collectset', 'indexTime'));
                }
            }
        } else {
            //获取缓存数据
            $data = $this->getIndexData();
        }

        // 轮播数据
        $banner = $this->getBanner();
        // 广告代码
        $ad = $this->getAdData();

        // 网站配置信息
        $cof = $this->getCof('index');
        return view($this->getTemplate("index"), ['data' => $data, "cof" => $cof, 'banner' => $banner, 'ad' => $ad]);
    }

    //加载
    public function jzad()
    {
        return  view($this->getTemplate("jzad"));
    }

    // 列表
    public function list()
    {

        // 请求信息
        $request = request();
        //请求数据
        $page = input();

        try {
            // 判断是否开启缓存
            if (getConfig('collectset', 'listSw') == "true") {
                //获取缓存数据
                $data = Cache::store("cmslistcache")->get($request->path());
                //判断缓存数据是否过期
                if (!$data) {
                    //获取数据
                    $data = $this->getMethod($page['vt'], $page);
                    $auth = json_decode($data, true);
                    //判断数据是否正常
                    if (isset($auth['code']) && $auth['code'] == "200") {
                        //数据缓存 时间单位秒
                        Cache::store("cmslistcache")->set($request->path(), $data, getConfig('collectset', 'listTime'));
                        //获取数据
                        $index = $this->getIndexData();
                        //判断数据是否正常
                        if (isset($index[0]['code']) && $index[0]['code'] == "200") {
                            //数据缓存 时间单位秒
                            Cache::store('cmsindexcache')->set("index", $index, getConfig('collectset', 'indexTime'));
                        }
                    }
                }
            } else {
                //获取数据
                $data = $this->getMethod($page['vt'], $page);
                $auth = json_decode($data, true);
                //判断数据是否正常
                if (isset($auth['code']) && $auth['code'] == "200") {
                    //数据缓存 时间单位秒
                    Cache::store("cmslistcache")->set($request->path(), $data, getConfig('collectset', 'listTime'));
                }
            }

            //判断访问类型
            if ($request->ext() == "json") {
                //json数据
                return $this->putJsonData($data, $page);
            } else {
                //解析数据
                $data = json_decode($data, true);
                //获取页面参数
                $cof = $this->getCof("list", $data);

                // 判断数据是否存在
                if (empty($data)) {
                    return $this->error('页面不存在');
                }

                // 广告代码
                $ad = $this->getAdData($page['vt']);

                // 载入视图
                return view($this->getTemplate("list"), ["data" => $data, "page" => $page, "cof" => $cof, 'ad' => $ad]);
            }
        } catch (\Exception $th) {
        }
    }

    // 详情
    public function detail($vt)
    {
        // 请求信息
        $request = request();
        //请求数据
        $page = input();
        // 判断是否开启缓存
        if (getConfig('collectset', 'detailSw') == "true") {
            //获取缓存数据
            $data = Cache::store("cmsdetailcache")->get($request->path());
            //判断缓存数据是否过期
            if (!$data) {
                //获取数据
                $data = $this->getMethod($vt, $page, 'play');
                //数据缓存 时间单位秒 
                Cache::store("cmsdetailcache")->set($request->path(), $data, getConfig('collectset', 'detailTime'));
            }
        } else {
            //获取数据
            $data = $this->getMethod($vt, $page, 'play');
        }

        //判断访问类型
        if ($request->ext() == "json") {
            //json数据
            return $this->putJsonData($data, $page, 'play');
        } else {
            //解析数据
            $data = json_decode($data, true);
            //获取页面参数
            $cof = $this->getCof("play", $data);

            // 判断数据是否存在
            if (empty($data)) {
                return $this->error('影片资源已被删除，请换一部观看');
            }
            // 判断采集是否为空
            if (isset($data['code']) && $data['code'] == '404') {
                return $this->error('影片资源采集失败，欢迎联系管理员处理！');
            }

            // 广告代码
            $ad = $this->getAdData($vt);
            // dump($data);
            // exit;
            // 载入视图
            return view($this->getTemplate("detail"), ['data' => $data, "page" => $page, "cof" => $cof, 'ad' => $ad]);
        }
    }

    // 播放页
    public function play($vt)
    {
        // 请求信息
        $request = request();
        //请求数据
        $page = input();
        // 判断是否开启缓存
        if (getConfig('collectset', 'playSw') == "true") {
            //获取缓存数据
            $data = Cache::store("cmsplaycache")->get($request->path());
            //判断缓存数据是否过期
            if (!$data) {
                //获取数据
                $data = $this->getMethod($vt, $page, 'play');
                //数据缓存 时间单位秒 
                Cache::store("cmsplaycache")->set($request->path(), $data, getConfig('collectset', 'playTime'));
            }
        } else {
            //获取数据
            $data = $this->getMethod($vt, $page, 'play');
        }

        //判断访问类型
        if ($request->ext() == "json") {
            //json数据
            return $this->putJsonData($data, $page, 'play');
        } else {
            //解析数据
            $data = json_decode($data, true);
            //获取页面参数
            $cof = $this->getCof("play", $data);

            // 判断数据是否存在
            if (empty($data)) {
                return $this->error('影片资源已被删除，请换一部观看');
            }

            // 判断采集是否为空
            if (isset($data['code']) && $data['code'] == '404') {
                return $this->error('影片资源采集失败，欢迎联系管理员处理！');
            }

            // 广告代码
            $ad = $this->getAdData($vt);

            // 播放记录
            $record = $this->getPlays();

            session('userrecord', $record);

            // 载入视图
            return view($this->getTemplate("play"), ['data' => $data, "page" => $page, "cof" => $cof, 'ad' => $ad, 'record' => $record]);
        }
    }

    //搜索页
    public function search()
    {

        // 请求信息
        $request = request();
        //请求数据
        $input = input();
        //获取搜索值
        $wd = isset($input['wd']) ? $input['wd'] : session('swd');
        $from = isset($input['from']) ? $input['from'] : session('sfrom');
        // 判断不带参数直接访问
        if (empty($wd)) {
            return $this->error('请输入内容后再搜索');
        }
        // 判断不带搜索关键字
        if (empty($from)) {
            return $this->error('未知搜索配置');
        }

        // 判断是否开启缓存
        if (getConfig('collectset', 'searchSw') == "true") {
            $cachepath = $request->path() . "?wd=" . $wd . "&from=" . input('from');
            //获取缓存数据
            $data = Cache::store("cmssocache")->get($cachepath);
            //判断缓存数据是否过期
            if (!$data) {
                //获取数据
                $data = $this->getMethod('search', $input, 'search');
                //数据缓存 时间单位秒 
                Cache::store("cmssocache")->set($cachepath, $data, getConfig('collectset', 'searchTime'));
            }
        } else {
            //获取数据
            $data = $this->getMethod('search', $input, 'search');
        }

        //判断访问类型
        if ($request->ext() == "json") {
            //json数据
            return $this->putJsonData($data, $input, 'search');
        } else {
            session('swd', $wd);
            session('sfrom', $from);
            $input['wd'] = $wd;
            $input['from'] = $from;
            //解析数据
            $data = json_decode($data, true);
            //获取页面参数
            $cof = $this->getCof("search", $data);

            // 广告代码
            $ad = $this->getAdData();

            // 载入视图
            return view($this->getTemplate("search"), ["data" => $data, "page" => $input, "cof" => $cof, 'ad' => $ad]);
        }
    }

    #事件处理###############################################


    // 选择采集机制
    public function getMethod($vt, $info = [], $type = "list")
    {
        //初始化返回变量
        $data = json_encode([]);

        // 列表
        $method = config($vt . '.method');
        // 判断列表方法是否存在
        if (!empty($method) && $type == 'list') {
            // 采集器路径
            $path = CMS_COLLECTION_PATH . config($vt . '.collist') . '/index.php';
            //载入采集器
            require_once($path);
            // 判断是否采集
            if ($vt == config($vt . '.alias')) {
                $data = $method($info, $type);
                return $data;
            }
        }

        // 详情
        $sign = config($vt . '.sign');
        // 判断方法是否存在
        if (!empty($sign) && $type == 'play') {
            // 采集器路径
            $path = CMS_COLLECTION_PATH . config($vt . '.collist') . '/index.php';
            //载入采集器
            require_once($path);
            // 判断是否采集
            if ($info['type'] == config($vt . '.sign')) {
                // $cid = $info['type'] . '/' . $info['sign'];
                $data = $method($info, $type);
                return $data;
            }
        }


        // 判断指定参数是否存在
        if (isset($info['from'])) {
            // 配置文件名
            $name = $vt . '-' . trim($info['from']);
            // 搜索
            $so = config($name . '.sign');
            // 类型
            $bindtype = config($name . '.bindtype');
            // 判断方法是否存在
            if (!empty($so) && $type == 'search') {
                $method = config($name . '.method');
                // 采集器路径
                $path = CMS_COLLECTION_PATH . config($name . '.collist') . '/index.php';
                //载入采集器
                require_once($path);
                // 判断是否采集
                if ($bindtype == $type) {
                    $wd = $info['wd'];
                    $data = $method($wd);
                    return $data;
                }
            }
        }



        return;
        // return $this->error("页面不存在");
        // $sign = config($vt . '.sign');
        // dump($vt);
        // dump($info);
        // dump($method);
        // dump($type);
        // //判断是否存在改方法
        // if ($method || $sign) {
        //     $path = CMS_COLLECTION_PATH . config($vt . '.collist') . '/index.php';
        //     require_once($path);
        //     //判断采集类型
        //     if ($type == 'list') {
        //         $data = $method($info, $type);
        //         dump($type);
        //     } else {
        //         $data = $method($info, $type);
        //         dump($data);
        //     }
        // }

        // // exit;
        // return $data;
        // 获取列表数据
        switch ($vt) {
            case 'dy':
                $data = getDyList($info);
                break;
            case 'tv':
                if ($type == "list") {
                    $data = getDsList($info);
                } else {
                    $data = getDsdeta($info);
                }
                break;
            case 'dm':
                $data = getDmList($info);
                break;
            case 'zy':
                $data = getZyList($info);
                break;
            case 'm':
                $data = getDydeta($info);
                break;
            case 'ct': //动漫信息
                $data = getDmdeta($info);
                break;
            case 'va': //综艺信息
                $data = getZydeta($info);
                break;
            default:
                return [];
                break;
        }
        return $data;
    }

    //首页数据
    public function getIndexData()
    {
        $request = Request::instance();

        // 初始化参数
        $data = [];
        $ds = [];
        $emp = false;
        // 获取所有专题配置
        // $filename = getFileName(APP_EXTRA_PATH, '.php');
        // $i = 0;
        // // 排序
        // foreach ($filename as $key => $value) {
        //     $sort = config($value['val'] . '.sort');
        //     $auth = config($value['val'] . '.index');
        //     $auths = config($value['val'] . '.close');
        //     if ($auth && $auths) {
        //         $ds[$i]['sort'] = $sort;
        //         $ds[$i]['val'] = $value['val'];
        //         $i++;
        //     }
        // }
        foreach (getConfig('navset') as $key => $value) {
            if ($value['overall'] == 'on') {
                $ds[$key]['sort'] = $value['sort'];
                $ds[$key]['val'] = $value['id'];
            }
        }
        arsort($ds);
        //获取数据
        foreach ($ds as  $key => $value) {
            $page['vt'] = $value['val'];
            // dump($value);
            $cachename = 'list/' . @$value['val'] . '-all-all-all-rankhot-1';
            $data[$key] = json_decode(Cache::store("cmslistcache")->get($cachename), true);
            // if (empty($data[$key])) {
            //     $emp = true;
            // }
        }

        // if ($emp) {
        //     try {
        //         $c = getConfig('navset');
        //         foreach ($c as $key => $value) {
        //             if ($value['overall'] == 'on') {
        //                 $url = $request->domain() . $value['url'];
        //                 // file_get_contents($request->domain() . $value['url']);
        //                 // file_get_contents($url);
        //                 $this->getReq($url);
        //             }
        //         }
        //         return $this->getIndexData();
        //     } catch (\Exception $th) {
        //     }
        // }
        return $data;
    }

    // 初始化页面信息
    public function getCof($page, $info = [])
    {
        // 网站配置信息
        $webset = getConfig("webset");
        // 默认SEO信息
        $seoset = getConfig("seoset");
        // 提示信息
        $tipsset = getConfig("tipsset");

        //判断是否自动SEO
        if (getConfig('seoset', "seo") == "on") {
            try {
                //首页
                if ($page == "index") {
                    $cof = [
                        "title" => @$webset['title'] . " - " . @$webset['subheading'],
                        "keywords" => @$seoset['keywords'],
                        "description" => @$seoset['description'],
                        'logo' => @$webset['logo'],
                        'copyright' => @$webset['copyright'],
                        "rgSwitch" => isset($tipsset['rgSwitch']) ? $tipsset['rgSwitch'] : '',
                        "rollgg" => @$tipsset['rollgg'],
                        "census" => @$webset['census'],
                        "timer" =>  $this->getEndTime() . "s"
                    ];
                    return $cof;
                }

                // 列表页
                if ($page == "list") {
                    $title = isset($info['type']['title']) ? $info['type']['title'] : '';
                    $timer = isset($info['consume']) ? $info['consume'] : 0;
                    $cof = [
                        "title" => @$webset['title'] . " - " . $title,
                        "keywords" => @$seoset['keywords'],
                        "description" => @$seoset['description'],
                        'logo' => @$webset['logo'],
                        'copyright' => @$webset['copyright'],
                        "census" => @$webset['census'],
                        "timer" => str_replace("s", "", $timer) + $this->getEndTime() . "s"
                    ];
                    return $cof;
                }

                // 播放页
                if ($page == "play") {
                    $title = isset($info['data']['vod_title']) ? $info['data']['vod_title'] : '';
                    @$keywords = implode(",", isset($info['data']['vod_type']) ? $info['data']['vod_type'] : []) . $info['data']['vod_title'] . "," . implode(",",  isset($info['data']['vod_actor']) ? $info['data']['vod_actor'] : []);
                    $cof = [
                        "title" => @$webset['title'] . " - " . $title,
                        "keywords" => @$seoset['keywords'] . "," . $keywords,
                        "description" => @$info['data']['vod_desc'],
                        'logo' => @$webset['logo'],
                        'copyright' => @$webset['copyright'],
                        "pgDataSwitch" => isset($tipsset['pgDataSwitch']) ? $tipsset['pgDataSwitch'] : '',
                        "playergg" => @$tipsset['playergg'],
                        "census" => @$webset['census'],
                        "timer" => str_replace("s", "", @$info['consume']) + $this->getEndTime() . "s"
                    ];
                    return $cof;
                }

                //搜索页
                if ($page == "search") {
                    //描述
                    $description = isset($info['data'][0]['vod_desc']) ? $info['data'][0]['vod_desc'] : $seoset['description'];
                    //关键词
                    $keyword = $seoset['keywords'];
                    $keywords = [];
                    if (isset($info['data'])) {
                        foreach ($info['data'] as $key => $value) {
                            $keywords[$key] = $value['vod_title'];
                        }
                    }
                    $keyword .= implode(",", $keywords);
                    $cof = [
                        "title" => @$webset['title'] . " - " . @$info['search'],
                        "keywords" => $keyword,
                        "description" => $description,
                        'logo' => @$webset['logo'],
                        'copyright' => @$webset['copyright'],
                        "census" => @$webset['census'],
                        "timer" => str_replace("s", "", @$info['consume']) + $this->getEndTime() . "s"
                    ];
                    return $cof;
                }
            } catch (\Exception $th) {
                $cof = [
                    "title" => @$webset['title'] . " - " . @$seoset['seotitle'],
                    "keywords" => @$seoset['keywords'],
                    "description" => @$seoset['description'],
                    'logo' => @$webset['logo'],
                    'copyright' => @$webset['copyright'],
                    "census" => @$webset['census'],
                    "timer" =>  $this->getEndTime() . "s"
                ];
                return $cof;
            }
        } else {
            $cof = [
                "title" => @$webset['title'] . " - " . @$seoset['seotitle'],
                "keywords" => @$seoset['keywords'],
                "description" => @$seoset['description'],
                'logo' => @$webset['logo'],
                'copyright' => @$webset['copyright'],
                "census" => @$webset['census'],
                "timer" =>  $this->getEndTime() . "s"
            ];
            return $cof;
        }
    }

    //选择模板并载入视图
    public function getTemplate($filename)
    {
        session('cms_page_visit', true);
        //判断是否启用PC移动自适应
        if (getConfig("webset", "adapt") == "true") {
            //判断是否是移动端设备
            if (is_mobile()) {
                $path = getConfig('webset', 'm_tem') . "/" . $filename;
            } else {
                $path = getConfig('webset', 'pc_tem') . "/" . $filename;
            }
        } else {
            $path = getConfig('webset', 'pc_tem') . "/" . $filename;
        }
        //判断模板文件是否存在
        if (file_exists(APP_PATH . "index/view/" . $path . "." . config("default_return_type"))) {
            return $path;
        } else {
            exit("模板已损坏或模板文件不存在");
        }
    }

    // 断点时间
    public function getEndTime()
    {
        $endtime = microtime(true);
        return  round($endtime - APP_RUN_STARTTIME, 3); //页面消耗时间
    }

    //输出api数据
    public function putJsonData($data, $info, $type = "list")
    {
        //判断是否开启接口 或者 站内访问
        if (getConfig("apiset", "apiSwitch") == "on" || session('cms_page_visit')) {
            //判断白名单
            if (in_array($_SERVER["REMOTE_ADDR"], explode(",", getConfig("apiset", "apiRoster"))) || getConfig("apiset", "apiRoster") == "*" || session('cms_page_visit')) {
                //判断是否读取缓存
                if (getConfig("apiset", "apiDataSwitch") != "on") {
                    if ($type == "list") { //列表
                        //获取数据
                        $data = $this->getMethod($info['vt'], $info);
                    } else if ($type == "search") { //搜索
                        //获取数据
                        $data = getSoList($info);
                    } else if ($type == "play") { //播放
                        //获取数据
                        $data  = $this->getMethod($info['vt'], $info['vt'] . "/" . $info['sign'], 'play');
                    } else {
                        $data = [];
                    }
                }
                //返回JSON数据
                return $data;
            } else {
                exit("未授权" . $_SERVER["REMOTE_ADDR"]);
            }
        } else {
            exit("api未开放");
        }
    }

    // 404
    public function miss()
    {
        // 是否是首页
        if (Request::instance()->url() == '/') {
            return $this->index();
        }
    }
}
